package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        //设置日期
        List<LocalDate> DateList = getDateList(begin, end);
        //获取营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : DateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("Status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByTimeAndStatus(map);
            if (turnover == null) {
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(DateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //设置日期
        List<LocalDate> DateList = getDateList(begin, end);
        //获取新用户
        List<Integer> NewUserList = new ArrayList<>();
        //获取总计用户
        List<Integer> TotalUserList = new ArrayList<>();

        for (LocalDate date : DateList) {
            Map<String,Object> map = new HashMap<>();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            map.put("endTime",endTime);
            Integer totalNum = userMapper.getNumByTime(map);
            if (totalNum == null) {
                totalNum = 0;
            }
            TotalUserList.add(totalNum);

            map.put("beginTime",beginTime);
            Integer NewUserNum = userMapper.getNumByTime(map);
            if (NewUserNum == null) {
                NewUserNum = 0;
            }
            NewUserList.add(NewUserNum);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(DateList,","))
                .newUserList(StringUtils.join(NewUserList,","))
                .totalUserList(StringUtils.join(TotalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> DateList = getDateList(begin, end);

        //总共订单集合
        List<Integer> TotalOrderList = new ArrayList<>();
        //有效订单集合
        List<Integer> validOrderList = new ArrayList<>();

        for (LocalDate date : DateList) {
            Map<String,Object> map = new HashMap<>();

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //添加总计订单数据
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer totalOrder = orderMapper.countByMap(map);
            if (totalOrder == null) {
                totalOrder = 0;
            }
            TotalOrderList.add(totalOrder);

            //添加有效订单数据
            map.put("Status", Orders.COMPLETED);
            Integer validOrder = orderMapper.countByMap(map);
            if (validOrder == null) {
                validOrder = 0;
            }
            validOrderList.add(validOrder);
        }

        Integer totalOrderSum = TotalOrderList.stream().reduce(Integer::sum).get();
        Integer validOrderSum = validOrderList.stream().reduce(Integer::sum).get();

        double Rate = 0.0;
        if(totalOrderSum!=0){
            Rate = validOrderSum.doubleValue()/totalOrderSum;
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(DateList,","))
                .orderCountList(StringUtils.join(TotalOrderList,","))
                .validOrderCountList(StringUtils.join(validOrderList,","))
                .validOrderCount(validOrderSum)
                .totalOrderCount(totalOrderSum)
                .orderCompletionRate(Rate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = orderMapper.top10(beginTime,endTime);
        List<String> NameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String name = StringUtils.join(NameList, ",");

        List<Integer> NumberList = list.stream().map(GoodsSalesDTO::getSumNumber).collect(Collectors.toList());
        String number = StringUtils.join(NumberList, ",");

        return SalesTop10ReportVO.builder().nameList(name).numberList(number).build();
    }


    @Override
    public void export(HttpServletResponse response) throws Exception {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        LocalDate today = LocalDate.now();
        LocalDateTime beginTime = LocalDateTime.of(today.plusDays(-30), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(today.plusDays(-1), LocalTime.MAX);
        if (is != null) {
            //设置时间
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间："+beginTime+"至"+endTime);
            //设置概览数据
            BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //设置明细数据
            for (int i = 0; i < 30; i++) {
                //设置当天具体时间
                LocalDate tempTime = today.plusDays(i-30);
                LocalDateTime tempBeginTime = LocalDateTime.of(tempTime,LocalTime.MIN);
                LocalDateTime tempEndTime = LocalDateTime.of(tempTime,LocalTime.MAX);
                row = sheet.getRow(7 + i);
                //获取当天数据
                BusinessDataVO TempBusinessData = workspaceService.getBusinessData(tempBeginTime, tempEndTime);
                //设置日期
                row.getCell(1).setCellValue(tempTime.toString());
                row.getCell(2).setCellValue(TempBusinessData.getTurnover());
                row.getCell(3).setCellValue(TempBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(TempBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(TempBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(TempBusinessData.getNewUsers());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            is.close();
            workbook.close();

        }
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> DateList = new ArrayList<LocalDate>();
        //设置日期
        DateList.add(begin);
        while (!begin.plusDays(1).equals(end)) {
            begin = begin.plusDays(1);
            DateList.add(begin);
        }
        return DateList;
    }
}
